/**
 * Place view uses a switcher widget to show information, reviews and a map of a single place.
 */

(function() {
	var view = View("place-view");

	var templates = {
		tabs: '<table class="place-links" summary="Tabs" cellspacing="0" cellpadding="0" border="0"><tr>' +
			'<td><div class="#{infoClass}" #{infoOnclick}>#{infoName}</div></td>' +
			'<td><div class="#{mapClass}" #{mapOnclick}>#{mapName}</div></td>' +
			'<td><div class="#{reviewsClass}" #{reviewsOnclick}>#{reviewsName}</div></td>' +
			'</tr></table>',
		details: sprintf('<div class="details">'+
			'#{displayimage}'+
			'<div class="info">'+
			'<table summary="Info" cellspacing="0" cellpadding="0" border="0"><tr>'+
			'<td class="address">#{displayaddress}</td>'+
			'<td class="rating">#{displayrating}</td>'+
			'</tr></table>'+
			'<div class="header">%s</div>'+
			'<div>#{displayopeninghours}</div>'+
			'<table class="buttons" summary="Buttons" cellspacing="0" cellpadding="0" border="0"><tr>'+
			'<td class="callto">#{displaycallto}</td>'+
			'<td class="webpage">#{displayurl}</td>'+
			'</tr></table>'+
			'</div>', qype.strings.openingHours),
        review: '<div class="review">'+
			'<table summary="ReviewRating" cellspacing="0" cellpadding="0" border="0"><tr>'+
			'<td><div class="review-user">#{user}</div></td>'+
			'<td class="rating">#{stars}</td>'+
			'</tr></table>'+
            '<div class="subject" id="#{idSummary}" onclick="mwl.hide(\'##{idSummary}\');mwl.show(\'##{idFullText}\');">#{summary}</div>'+
            '<div class="fullText" id="#{idFullText}" onclick="mwl.hide(\'##{idFullText}\');mwl.show(\'##{idSummary}\');" style="display: none;">#{fullText}</div>'+
            '</div>'
	};
	
	qype.views.placeView = view;
	
	var toggle;
	var loading;
	var header;
	var tabs;
	var description;
	var reviews;
	var reviewsList;
	var reviewsLoading;
	var map;
	var mapImage;

	view.getHtml = function() {
		return sprintf('<div id="%s"></div>', view.getId());
	};

	var backId = view.getId() + "-back";

	function getTabsLinks(index) {
		var data = {
			infoOnclick: index == 0 ? '' : sprintf('onclick="%s"', tabs.linkMwl(0)),
			reviewsOnclick: index == 1 ? '' : sprintf('onclick="%s"', tabs.linkMwl(1)),
			mapOnclick: index == 2 ? '' : sprintf('onclick="%s"', tabs.linkMwl(2)),
			infoClass: index == 0 ? ' selected-tab' : 'tab',
			reviewsClass: index == 1 ? ' selected-tab' : 'tab',
			mapClass: index == 2 ? ' selected-tab' : 'tab',
			infoName: qype.strings.info,
			reviewsName: qype.strings.reviews,
			mapName: qype.strings.map
		};
		return util.template(templates.tabs, data);
	}
	
	view.init = function() {
		this.initBack();
		toggle = ToggleWidget();
		view.getContainer().append(toggle.getHtml());
		loading = LoadingWidget({label: qype.strings.loading});
		toggle.setContent(0, "<h1>&nbsp;</h1>" + loading.getHtml());
		header = ElementWidget({id: view.getId() + "-header", tag: "h1"});
		tabs = SwitcherWidget();
		toggle.setContent(1, header.getHtml() + tabs.getHtml());
		description = ElementWidget({id: "place-description"});
		tabs.addView(getTabsLinks(0) + description.getHtml());
		reviews = ElementWidget({id: "place-reviews"});
		tabs.addView(getTabsLinks(1) + reviews.getHtml());
		reviewsList = ListWidget({id: "place-reviews-list", emptyContent: sprintf('<div class="no-results">%s</div>', qype.strings.place_no_reviews)});
		reviewsLoading = LoadingWidget({label: qype.strings.loading});
		reviews.html(reviewsList.getHtml() + reviewsLoading.getHtml());
		reviewsList.hide();
		reviewsLoading.show();
		map = ElementWidget({id: "place-map"});
		tabs.addView(getTabsLinks(2) + map.getHtml() + '<div class="map-marker">&nbsp;</div>');
	};
	
	view.setLinks = function(links) {
		this.addBack(backId, links.backToPlaces);
		this.showBack(backId);
	};
	
	view.loadPlace = function(placedata) {
		function cleanNumber(number) {
			number = number || "";
			number = number.replace(/[^0-9+]/g,"");
			var hasPlus = number.match(/^\+/);
			number = number.replace(/[^0-9]/g,"");
			return (hasPlus ? "+" : "") + number;
		}
		
		var place = qype.models.PlaceModel(placedata);

        placedata.displayimage = placedata.image ? "<div class=\"image\"><img src='" + place.getImageUrl("medium2x") + "' class='main' /></div>" : "";
		if(placedata.address) placedata.displayaddress = sprintf('<div class="line">%s %s</div><div class="line">%s %s</div>', 
			placedata.address.housenumber || "", placedata.address.street || "", 
			placedata.address.postcode || "", placedata.address.city || "");
		placedata.displayopeninghours = (placedata.opening_hours || qype.strings.notAvailable).replace("\n","<br />");

		placedata.displayrating = '<div class="image-holder"><img class="stars'+placedata.average_rating+'" src="img/star.png" /></div>' + place.getReviewsStr();

		var phoneClean = cleanNumber(placedata.phone);
		if(phoneClean) placedata.displaycallto = '<div class="button"><a href="tel:' + phoneClean + '"">' + qype.strings.place_call + '</a></div>';
		if(placedata.url) placedata.displayurl = '<div class="button"><a href="' + placedata.url + '">' + qype.strings.place_open_www + '</a></div>';

		header.html(placedata.title);
		tabs.showView(0);
		description.html(util.template(templates.details, placedata));
		reviewsList.populate([]);
		if(place.getReviewsCount() > 0) {
			reviewsList.hide();
			reviewsLoading.show();
			this.loadReviews(place.getId(), place.contentLang);
		} else {
			reviewsList.show();
			reviewsLoading.hide();
		}
		if(placedata.point) {
			var loc = placedata.point.split(',');
			var height = 220;
			var distance = place.getDistanceStr();
			distance = distance ? sprintf('<div class="map-distance">%s</div>', sprintf(qype.strings.distance, distance)) : '';
			map.html(sprintf('%s<div style="background: no-repeat url(\'%s\') center; height: %spx;">&nbsp;</div>', distance, new MapImage({
				center : { lat : loc[0] , lon : loc[1] }, 
				zoom : 15, 
			    overlays : { scale : false, dot : false },
				size : { width : util.width(), height : height } 
			}).getUrl(), height));
		} else {
			map.html(qype.strings.noLocation);
		}
		toggle.showContent(1);
	};
	
	function reviewsToListItems(reviews) {
		return $.map(reviews, function(item, index) {
			var review = item.review;
			var content = util.template(templates.review, {
				summary: review.summary,
				fullText: review.content_xhtml,
				idSummary: review.id + "-summary",
				idFullText: review.id + "-fullText",
				user: (util.getLink(review, /user$/) || {title: ''}).title || '',
				stars: '<div class="image-holder"><img class="stars' + review.rating + '" src="img/star.png" /></div>'
			});
			return {content: content};
		});
	}
	
	view.loadReviews = function(placeId, placeLang) {
		qype.API.get("places", {
	        onSuccess: function(response) {
				reviewsList.populate(reviewsToListItems(response.results));
				reviewsList.show();
				reviewsLoading.hide();
	        },
	        onFailure: function(response, status) {
				reviewsList.populate([]);
				reviewsList.hide();
				reviewsLoading.setError(util.networkErrorMessage(status, reviewsLoading.showLoadingMwl() + sprintf("qype.views.placeView.loadReviews.call(qype.views.placeView,'%s','%s');", placeId, placeLang)));
				reviewsLoading.showError();
				reviewsLoading.show();
	        }
		}, placeId + '/reviews/' + placeLang);
	};
	
	view.resetMwl = function() {
		return toggle.showContentMwl(0) + reviewsLoading.showLoadingMwl();
	};
	
})();
